from PySide6.QtCore import Qt, Signal, QTime
from qfluentwidgets import SettingCard, FluentIconBase, TimePicker, qconfig

class TimePickerSettingCard(SettingCard):
    """ 时间选择设置卡片 """
    
    timeChanged = Signal(str)  # 时间改变信号

    def __init__(self, icon: FluentIconBase, title: str, content: str, 
                 configItem, parent=None):
        super().__init__(icon, title, content, parent)
        self.configItem = configItem
        
        # 创建时间选择器
        self.timePicker = TimePicker(self)
        
        # 从配置中读取保存的值
        if configItem:
            saved_time = qconfig.get(configItem)
            if saved_time:
                self.setTime(saved_time)
            configItem.valueChanged.connect(self.setTime)
        
        self.timePicker.setMinimumWidth(160)
        # 显示秒数列
        self.timePicker.setColumnVisible(2, True)
        
        # 将时间选择器添加到右侧
        self.hBoxLayout.addWidget(self.timePicker, 0, Qt.AlignRight)
        self.timePicker.timeChanged.connect(self._onTimeChanged)

    def _onTimeChanged(self, time: QTime):
        """ 时间改变时的处理 """
        if self.configItem:
            # 将 QTime 转换为字符串后再保存，包含秒数
            time_str = time.toString("HH:mm:ss")
            qconfig.set(self.configItem, time_str)
        self.timeChanged.emit(time.toString("HH:mm:ss"))

    def getTime(self) -> str:
        """ 获取当前时间值 """
        return self.timePicker.time().toString("HH:mm:ss")

    def setTime(self, time_str: str):
        """ 设置时间值 
        Args:
            time_str: 时间字符串，格式为 "HH:mm:ss" 或 "HH:mm"
        """
        try:
            # 将字符串转换为 QTime 对象
            time_parts = time_str.split(':')
            if len(time_parts) == 3:  # HH:mm:ss
                hour = int(time_parts[0])
                minute = int(time_parts[1])
                second = int(time_parts[2])
                time = QTime(hour, minute, second)
            elif len(time_parts) == 2:  # HH:mm
                hour = int(time_parts[0])
                minute = int(time_parts[1])
                time = QTime(hour, minute, 0)
            else:
                time = QTime(0, 0, 0)

            if time.isValid():
                self.timePicker.setTime(time)
            else:
                self.timePicker.setTime(QTime(0, 0, 0))
        except (ValueError, AttributeError):
            self.timePicker.setTime(QTime(0, 0, 0))
        